package com.sjsoft.video;

import java.util.ArrayList;

import android.R.anim;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.os.AsyncTask;

import com.sjsoft.Utils.networkUtility;
import com.sjsoft.adapter.VideoAdapter;
import com.sjsoft.app.video.R;
import com.sjsoft.application.chatVideoApp;
import com.sjsoft.chat.video.ListVideo;
import com.sjsoft.model.videoItem;
import com.sjsoft.webservice.UtilsJson;

public class LoadItemsVideo extends AsyncTask<Void, Void, Void>{

	
	protected chatVideoApp application;
	int resultRequest;	
	boolean isNetWork = true;
	String id;
	Context mContext;
	int nIndex;
	ArrayList<videoItem> list = null; //Return list video to push to adapter
	//Constructor
	private ProgressDialog pDlg = null;
	public LoadItemsVideo(Context context,String sId,int nIndex,ProgressDialog dlg) {
		this.id = sId;
		mContext = context;
		this.nIndex = nIndex;
		isNetWork = networkUtility.getInstance(context)
				.isNetworkAvailable();
		this.application = (chatVideoApp) context.getApplicationContext();
		this.pDlg = dlg;
		
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();		
	}

	@Override
	protected Void doInBackground(Void... params) {
		if (isNetWork) {
			//application.videoCategory = UtilsJson.getCategoryVideo();
			//String sCategory = UtilsJson.getCategoryVideo(id);
			
			chatVideoApp.appendLog("get data at id = "+id + " pos start " + nIndex);
			String sResult = "";
			if(nIndex == 0)
			{
				sResult = UtilsJson.getItemsVideo(id,nIndex,nIndex+4);
			}
			else
				sResult = UtilsJson.getItemsVideo(id,nIndex,nIndex+2);
			
			list = UtilsJson.getListVideoFromJson(sResult);
			int nSize = list.size();
			for(int i = 0; i < nSize; i++)
			{
				videoItem item = list.get(i);
				String jsonMsg = UtilsJson.getListChat(item.getProfileId());
				item = UtilsJson.getListMessageFromJson(jsonMsg,item);
				//item.setMessage(arrMsg);
				list.set(i, item);
			}
			application = ((chatVideoApp)mContext.getApplicationContext());
			if(nSize == 0)
				application.bLastData = true;
			
		} 
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		if(list != null && list.size() > 0)
		{
			VideoAdapter adapter = new VideoAdapter(mContext);
			adapter.addItems(list);
			((ListVideo)mContext).updateListVideo(adapter);//Thien_vv
		}
		else
		{
			//((ListVideo)mContext).refreshLastest();
			chatVideoApp.appendLog("have no data at id = "+id);
		}
		if(pDlg != null)
			pDlg.dismiss();
	}
}

